import os
import tempfile
import gfx

from Products.PortalTransforms.interfaces import itransform

class PdfToFlash:
    """ convert pdf file to flash with gfx, swftools python module """
    __implements__ = itransform

    __name__ = "pdf_to_flash"
    inputs   = ('application/pdf',) 
    output   = 'application/x-shockwave-flash'

    def name(self):
        return self.__name__

    def convert(self, orig, data, **kwargs):

        #temp_file = tempfile.NamedTemporaryFile('w')
        #temp_file.write(orig)
        #temp_file.seek(0)
        temp_file_name = tempfile.mktemp()
        fh = open(temp_file_name, 'w')
        fh.write(orig)
        fh.close()

        doc = gfx.open("pdf", temp_file_name)
        swf = gfx.SWF()
        for pagenr in range(1, doc.pages+1):
            page = doc.getPage(pagenr)
            swf.startpage(page.width, page.height)
            page.render(swf)
            swf.endpage()


        #temp_file.seek(0) # serve???? tanto dovrei sovreascrivere
        #temp_file.close()
        #temp_file = tempfile.NamedTemporaryFile('w')
        #swf.save(temp_file.name)
        swf.save(temp_file_name)

        #swf.save('test_document.swf')

        #temp_file.seek(0)
        fh = open(temp_file_name,'r')
        data.setData(fh.read())
        #import pdb; pdb.set_trace()
        #temp_file.close()
        fh.close()
        os.unlink(temp_file_name)
        return data

def register():
    return PdfToFlash()
